var tabs;
var tabCount = 0;
var calCount = 0;
var selCount = 0;
var tabObject;
var newFamilyID;
var clientInfoTabs;

var comboWithTooltip1;
var comboWithTooltip2;
var comboWithTooltip3;

/*
 * Data stores
 */
var schoolDistrictStore;
var roleProfessionalStore;
var diagnosisStore;
	
var newContactInitObj = {
	createClientInformationTabs : function() {
		if (!clientInfoTabs) {
			clientInfoTabs = new Ext.TabPanel({
		        renderTo:  'clientInformationTabs',
		        width:     750,
				activeTab: 0,
		        plain:     true,			
				enableTabScroll: true,
		        defaults:  {
		        	autoHeight: true
		        },
		        items:[
		            {contentEl:'tabClientInfo1', title: 'Social/Recreational'},
					{contentEl:'tabClientInfo2', title: 'School/Transition'},
					{contentEl:'tabClientInfo3', title: 'Family'},
					{contentEl:'tabClientInfo4', title: 'Trainings/Events'},
					{contentEl:'tabClientInfo5', title: 'Library'},
					{contentEl:'tabClientInfo6', title: 'Partners'},
					{contentEl:'tabClientInfo7', title: 'Subscriptions'}
	        ]
		    });	
		}			    
	},	
	createFamilyTabs : function() {	
		if (!tabs) {
			tabs = new Ext.TabPanel({
		        renderTo:        'familyTabs',
				plain:           true,
		        resizeTabs:      true,
				enableTabScroll: true,
				minTabWidth:     150,
		        width:           750,
				height:          540,
		        defaults:        {
		        	autoScroll: true
		        },
		        listeners:       {
		        	beforeremove: function(tabs,tab) {
		        		contactSaveFamilyTeamObj.removeTeamMemberFromContact(tab.id);
		        	}        
		        }
		    });	    
		}		    
	},
}

var contactFormSupportObj = {
	loadData : function() {
		/*
		 * School districts
		 */
		schoolDistrictStore = new Ext.data.JsonStore({
			root:   'Districts',
	        fields: ['DistID', 'District'],
	        data :  Ext.jsonData.schoolDistricts
	    });
	    
	    /*
	     * Roles Professional
	     */
	    roleProfessionalStore = new Ext.data.Store({
		    proxy: new Ext.data.HttpProxy({
				url: 'ajaxDirector.php?handler=getRoles&memberType=Professional&renderType=json&org=OrPTI'
		    }),
			
		    reader: new Ext.data.JsonReader({
		        root: 'Roles',
		        id: 'RoleID'
		    }, [			
				{name: 'RoleID', mapping: 'RoleID'},
				{name: 'Role',  mapping: 'Role'}
		    ])		
		});
		roleProfessionalStore.load();
			
		/*
		 * Get events
		 */
		getEventsObj.getEventsForContactForm('referral'); // <- In jsCalendar.js 
	},
	showReferralPanel : function(referralItem,toggle) {
		var checkboxID = referralItem+'Items';
		var panelID = 'panel'+checkboxID;
		this.closeAllReferralContentPanels();
		if ($(checkboxID).checked == true) {
			new Effect.SlideDown(panelID, {direction: 'top', duration: .3});
			if (panelID == 'panelLibraryItems') {
				contactFormSupportObj.autocompleterFieldsLibrary();
			}
			
		} else {
			if ($(panelID).style.display == '') {
				this.hideReferralPanel();
			}	
		}	
		if (toggle == 1) {
			// Toggle referral item in database
			contactSaveReferralInfoObj.toggleReferralItem(referralItem);
		}	
	},
	hideReferralPanel : function(panelID) {
		new Effect.SlideUp(panelID, {direction: 'top', duration: .3});
	},
	closeAllReferralContentPanels : function() {
		var contentPanels = document.getElementsByClassName('checkboxContent');
		for(i = 0; i < contentPanels.length; i++) {
			// Close any open panels
			contentPanels[i].style.display = 'none';
		}
	},
	renderOrgCombo : function() {
		var orgSelectConverted = new Ext.form.ComboBox({
			typeAhead:     true,
	        triggerAction: 'all',
	        transform:     'selectOrganization',
	        width:         250,
			shadow:        false,			
			resizable:     true,
	        grow:          true,
	        growMax:       300,
	        growMin:       200,
	        listWidth:     250,
	        forceSelection:false
	    });			
	},
	addNewMemberTab : function(memberID) {
		var org = $F('org');
		if (!memberID) {
			memberID = 0;
		}
		tabCount++;
		tabs.add({
			id:        tabCount,
            title:     'New member',
			header:    true,
            autoLoad:  {
						url:     'includes/formModules/contactFormFamilyMembersOrPTI.php?memberID='+memberID, 
						params:  'id='+tabCount, 
						scripts: true
			},
            closable:  true,
            iconCls:   'iconPeople',
            autoWidth: true,
			listeners: {
				activate: this.tabActivate
			}
        }).show();		
        return tabCount;
	},
	tabActivate : function(tabObject) {
		var tabID = tabObject.id;
				
		/*
		 * Get Client Information data for this tab
		 */		
		contactFormGetInfoObj.getClientInfoInit(tabID);		
	},	
	closeAllFamilyTabs : function() {
		/*
		tabs.items.each(
			function(item) {
				if(item.closable) {
					tabs.remove(item,false);
				}	
			}
		);
		*/
		tabs.destroy();
		tabs = null;
	},
	addMemberTabElements : function(id) {
		/*
		 * Convert the school district select box to an Ext ComboBox
		 * so we can take advantage of type ahead and stuff.
		 */
		var schoolDistrict = new Ext.form.ComboBox({
			store:         schoolDistrictStore,
		    displayField:  'District',
		    valueField:    'DistID',
		    name:          'selectSchoolDistrict'+id,
		    typeAhead:     true,
		    mode:          'local',
		    triggerAction: 'all',
		    emptyText:     'Select...',
		    selectOnFocus: true,
			resizable:     true,
	        shadow:        false,
	        grow:          true,
	        growMax:       350,
	        growMin:       200,
	        width:         275,
			listWidth:     275,
	        handleHeight:  12,
		    applyTo:       'selectSchoolDistrict'+id
		});
		
		var dateFieldBirthName = 'dateFieldBirth'+id;		
		
		// Convert dateBirth field to Ext DateField	
		var dateBirth = new Ext.form.DateField({
			width: 90,
		    allowBlank: true,
		    format: 'm/d/Y',
			applyTo: dateFieldBirthName
		});
		
		// Init autocompleter fields
		this.autocompleterFieldsMember(id);
	},
	updateTabTitle : function(id,tabTitle) {
		/*
		 * Get tab object from tab id
		 */
		var tabObject = tabs.getItem(id);
		if (!tabTitle) {
			var nameFirst = 'nameFirst'+id;
			var nameLast  = 'nameLast'+id;
			var tabTitle = $F(nameFirst)+' '+$F(nameLast);
			var tabTitle = tabTitle.trim();
		}		
		
		if (tabTitle.length>0) {
			tabObject.setTitle(tabTitle);
		}	
	},
	showMemberTypePanel : function(memberType,id,disable,open) {
		var checkboxID = 'memberType'+memberType+id;
		var panelID    = 'panel'+memberType+id;		
		var allPanels  = document.getElementsByClassName('memberType'+id);
		
		// If memberType == Child, disable all other checkboxes because we can't
		// be a Child and a Parent at the same damn time.
		if ( (memberType == 'Child') && ($(checkboxID).checked == true) ) {
			$('memberTypeParent'+id).disabled = true;
			$('memberTypeProfessional'+id).disabled = true;
			$('memberTypeOther'+id).disabled = true;
		} else {
			$('memberTypeParent'+id).disabled = false;
			$('memberTypeProfessional'+id).disabled = false;
			$('memberTypeOther'+id).disabled = false;
		}
		
		if ( ($(checkboxID).checked == true) ) {
			// Clear any visible panels
			for(i=0;i<allPanels.length;i++) {
				allPanels[i].style.display = 'none';
			}
			
			// Now render selected member type options panel
			$(panelID).style.display = '';
		} else {
			$(panelID).style.display = 'none';
		}	
	},
	clearFollowUpMessage : function() {
		if ($F('followUpNotes') == 'Notes or Instructions:') {
			$('followUpNotes').value = '';
		}
	},
	clearAdditionalRecipients : function() {
		if ($F('followUpAdditionalRecipients') == 'Additional recipients: separate multiple email addresses with commas') {
			$('followUpAdditionalRecipients').value = '';
		}
	},
	showHidePartnerMatches : function() {
		var panelID = $('partnerMatchPanel');
		if ($('partnerMatchPanel').style.display == '') {
			new Effect.SlideUp(panelID, {direction: 'top', duration: .3});
			$('partnerMatchButton').innerHTML = 'Partner Matches';
			$('partnerMatchButton').className = 'search';
		} else {
			new Effect.SlideDown(panelID, {direction: 'top', duration: .3});
			$('partnerMatchButton').innerHTML = 'Close';
			$('partnerMatchButton').className = 'close';
		}
	},
	autocompleterFieldsMember : function(id) {
		var memberLookupLastNameURL = 'ajaxDirector.php?handler=getMembersForAutocompleter&autoComplete=1&SearchField=LastName&tabID='+id;
		var memberLookupPhoneURL    = 'ajaxDirector.php?handler=getMembersForAutocompleter&autoComplete=1&SearchField=Phone1&tabID='+id;
		
		new Ajax.Autocompleter('nameLast'+id, 'nameLastAutocompleter'+id, memberLookupLastNameURL, {paramName: "autoText", minChars: 3, updateElement: this.returnAutocompleterFieldsMember});
		new Ajax.Autocompleter('phone1'+id, 'phone1Autocompleter'+id, memberLookupPhoneURL, {paramName: "autoText", minChars: 3,  updateElement: this.returnAutocompleterFieldsMember});
	},
	returnAutocompleterFieldsMember : function() {
		/*
		 * Do nothing
		 */
	},
	setActiveMemberID : function (memberID) {
		$('activeMemberID').value = memberID;
	},
	setActiveFamilyID : function (familyID,type) {
		/*
		 * Do we need to update the familyID hidden field?
		 */
		if ($F('familyID') == 0) {
			/*
			 * If we're pulling info for a single member,
			 * and the form familyID = 0, then
			 * keep the familyID = 0 or else we'll be assigning
			 * the members' familyID to this contact when we really
			 * need to be re-assigning the member a new familyID
			 */
			if (type == 'member') {
				/*
				 * Get next available familyID and pass that as newFamilyID
				 */
				var params = 'handler=getNextFamilyID';
				var ajaxResults = new Ajax.Request('ajaxDirector.php', {
					method: 'POST',
					parameters: params,
					onSuccess: function(transport) {
						newFamilyID = transport.responseText;
					}
				});
			} else {
				/*
				 * Then update familyID
				 */
				$('familyID').value = familyID;
				/*
			 	* Don't change anybody's familyID
			 	*/
				newFamilyID = 0;	
			}						
		} else {
			/*
			 * These members now belong to another family
			 * namely, the family that has already been
			 * started for this contact
			 */
			newFamilyID = $F('familyID');
		}
		return newFamilyID;
	},
	autocompleterFieldsLibrary : function() {
		var librarySearchURL = 'ajaxDirector.php?handler=getLibraryItemsForAutocompleter&autoComplete=1';
		new Ajax.Autocompleter('librarySearchBox', 'librarySearchBoxAutocompleter', librarySearchURL, {paramName: "autoText", minChars: 2, updateElement: this.returnAutocompleterFieldLibrary});
	
	},
	returnAutocompleterFieldLibrary : function() {
		/*
		 * Do nothing
		 */
	},
	removeLibraryReferralItem : function(libraryID) {
		var contactID = $F('contactID');
		var params = 'handler=removeLibraryReferralItem&libraryID='+libraryID+'&contactID='+contactID;
		var ajaxResults = new Ajax.Request('ajaxDirector.php', {
			method: 'POST',
			parameters: params,
			onSuccess: function(transport) {
				var libraryID = transport.responseText;
				Effect.Fade('libraryReferralRow'+libraryID, {delay: .1, duration: 1});
			}
		});	
	},
	// TODO: Add clear Client Info tabs
	clearClientInfoTabs : function() {
		
	}
	
}

var deleteContacts = {
	deleteContact : function(contactID) {
		var params = 'handler=deleteContact&contactID='+contactID;
		var ajaxResults = new Ajax.Request('ajaxDirector.php', {
			method: 'POST',
			parameters: params,
			onSuccess: function(transport) {
				deleteContacts.returnDeleteContact(transport.responseText);
			}
		});
	},
	returnDeleteContact : function(contactID) {
		var rowEl = $('contactRow'+contactID);
		Effect.Fade(rowEl, {delay: .1, duration: 1});
	}
}

var viewTabContent = {
	content0Load : function() {
		contactFormSupportObj.loadData();
		newContactInitObj.createClientInformationTabs();		
		newContactInitObj.createFamilyTabs();
		
		/*
		 * Are we in add or edit mode?
		 */
		var mode = $F('action');
		var mainTabObject = mainTabs.getItem('pageTab0');
		if (mode == 'add') {
			$('contactSubject').focus();
			$('familyID').value = 0;
			
			/*
			 * Create first family member tab
			 */
			contactFormSupportObj.addNewMemberTab();	
			/*
			 * Set tab title
			 */
			mainTabObject.setTitle('New Contact');
			$('contactFormStatus').style.display = 'none';
		} else if (mode == 'edit') {
			/*
			 * Retrieve information and populate contact form
			 */
			var contactID = $F('contactID');		
			contactFormSupportObj.closeAllFamilyTabs();
			newContactInitObj.createFamilyTabs();
			contactFormGetInfoObj.getContactFormInfoForEdit(contactID);	
			/*
			 * Get notes for this contact
			 */
			getNoteDataObj.getNotesForContact(contactID);
		}
		/*
		new Form.Observer('contactForm', 0.3, function(form, value){
  		$('msg').update('Your preferences have changed. Resubmit to save').style.color = 'red'
  		form.down().setStyle({ background:'lemonchiffon', borderColor:'red' })
		})
		*/
	},
	content1Load : function() {
		if ($F('contactLogLoaded') != 1) {
			/*
			 * Load contact log data into grid
			 */
			var contactLogStart = $F('contactLogStart');
			getContactDataObj.getContactsForGrid('page',contactLogStart,20,0,0);			
		}	
	},
	viewContactInit : function(contactID) {
		$('action').value    = 'edit';
		$('contactID').value = contactID;
		mainTabs.setActiveTab('pageTab0');
	}
}

Ext.onReady(function() {
	
});
